<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/12/4
 * Time: 15:00
 */

namespace app\zyhsapi\model;

use app\common\lib\Util;
use app\zyhsapi\lib\OrdersLib;
use think\Log;

class ZyhsOrders extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_orders';

    protected $cacheModel = 'orders.orders';

    /**
     * 新增订单
     * @param       $data
     * @return int|string
     */
    public function SaveData($data)
    {
        try
        {
            $data['channel'] = Util::getChannelId();
            $oid = $this->insertGetId($data);
        }
        catch (\Exception $e)
        {
            Log::write('订单入库失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            return false;
        }
        return $oid;
    }

    public function UpdateData($orderId, $data)
    {
        try
        {
            $this->where('order_id', $orderId)->update($data);
        }
        catch (\Exception $e)
        {
            Log::write('ZyhsOrders model => ()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 从数据库批量获取订单信息,根据订单id
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|null
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $where = ['order_id' => ['in', $ids]];

        try
        {
            $data = $this->where($where)->order('id', 'DESC')->column('*', 'order_id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 订单退款
     * @param $orderId
     * @param $refundPrice
     * @param $refundReason
     * @return true
     * @throws \Exception
     */
    public function refund($orderId, $refundPrice, $refundReason)
    {
        $nowTime = time();
        $orderInfo = $this->getInfoById($orderId);
        $res = OrdersLib::UpdateCoin($orderId, $orderInfo['order_type'], $refundPrice, $orderInfo['uid'], 4, 4, '', $orderInfo['gid'],$refundReason);
        if ($res)
        {
            $this->UpdateData($orderId, ['status' => 3, 'return_time' => $nowTime]);
            (new ZyhsOrdersRefund())->SaveData([
                'uid' => $orderInfo['uid'],
                'order_id' => $orderId,
                'refund_price' => $refundPrice,
                'order_type' => $orderInfo['order_type'],
                'trade_type' => $orderInfo['trade_type'],
                'create_time' => $nowTime,
                'refund_reason' => $refundReason
            ]);
        }
        return true;
    }
}
